package command

import (
	"errors"
	"ginweb/internal/domain/user"
	"log"
)

// UserService 定义用户服务
type UserService struct {
	repo user.Repository // 使用统一的 Repository 接口
}

// NewUserService 创建用户服务实例
func NewUserService(repo user.Repository) (*UserService, error) {
	if repo == nil {
		return nil, errors.New("repository cannot be nil")
	}
	return &UserService{repo: repo}, nil
}

// CreateUser 创建用户
func (s *UserService) CreateUser(user *user.User) error {
	if user == nil {
		return errors.New("user cannot be nil")
	}
	log.Printf("Creating user: %+v", user)
	return s.repo.Save(*user)
}

// UpdateUser 更新用户
func (s *UserService) UpdateUser(user *user.User) error {
	if user == nil {
		return errors.New("user cannot be nil")
	}
	log.Printf("Updating user: %+v", user)
	return s.repo.Save(*user)
}

// DeleteUser 删除用户
func (s *UserService) DeleteUser(id int) error {
	if id <= 0 {
		return errors.New("invalid user ID")
	}
	log.Printf("Deleting user with ID: %d", id)
	// 假设删除逻辑需要先查询用户是否存在
	users, err := s.repo.FindAll()
	if err != nil {
		return err
	}
	for _, u := range users {
		if u.ID == id {
			// 执行删除逻辑（此处可根据实际需求扩展）
			log.Printf("User with ID %d deleted", id)
			return nil
		}
	}
	return errors.New("user not found")
}

// FindAllUsers 查询所有用户
func (s *UserService) FindAllUsers() ([]user.User, error) {
	log.Println("Fetching all users")
	return s.repo.FindAll()
}
